using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySpawner : MonoBehaviour
{
    [Header("生成设置")]
    public float spawnRadius = 8f; // 生成半径(玩家周围)
    public float safeDistance = 3f; // 安全距离(避免生成在玩家脸上)
    public int initialWaveSize = 5;// 初始波次大小
    public float waveCooldown = 10f;// 波次冷却时间
    public float waveSizeMultiplier = 1.2f;// 波次大小倍率
    
    private Transform player;
    private int currentWave = 0;

    private void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player").transform;
        StartCoroutine(WaveSpawner());
    }

    IEnumerator WaveSpawner()
    {
        while (true) // 无限波次循环
        {
            currentWave++;
            int enemiesToSpawn = Mathf.FloorToInt(initialWaveSize * Mathf.Pow(waveSizeMultiplier, currentWave - 1));
            
            // 生成一波敌人
            for (int i = 0; i < enemiesToSpawn; i++)
            {
                SpawnEnemy();
                yield return new WaitForSeconds(0.5f); // 间隔生成
            }
            
            yield return new WaitForSeconds(waveCooldown); // 波次间隔
        }
    }

    void SpawnEnemy()
    {
        // 计算随机位置(确保不在安全距离内)
        Vector2 spawnPos = GetRandomSpawnPosition();
        
        // 从对象池获取敌人
        GameObject enemy = EnemyPool.GetInstance().GetEnemy(spawnPos);
        
        // 初始化敌人
        enemy.GetComponent<EnemyController>().InitEnemy();
    }

    Vector2 GetRandomSpawnPosition()
    {
        Vector2 randomDir = Random.insideUnitCircle.normalized;
        float distance = Random.Range(safeDistance, spawnRadius);
        return (Vector2)player.position + randomDir * distance;
    }

    // 可视化生成范围(调试用)
    void OnDrawGizmosSelected()
    {
        if (player == null) return;
        
        Gizmos.color = Color.blue;
        Gizmos.DrawWireSphere(player.position, safeDistance);
        Gizmos.color = Color.green;
        Gizmos.DrawWireSphere(player.position, spawnRadius);
    }
}
